'''
This file is a part of nets7r project
Licensed under New BSD license
H3n0xek (C) 2011 
'''
from components import StateObject, IdentifiedObject
from components.ports import PortCollection


class Device(StateObject, IdentifiedObject):
    """Device has a number of ports which port-macs table"""
    
    class Meta(object):
        """Meta information of device"""
        display_name = None
    
    def __init__(self):
        """Initialize device: get ID and default state (turned off)
        
        
        Also initialize ports collection and table"""
        super(Device, self).__init__()
        self._ports = PortCollection(self._id)
        self.Meta.display_name = "Device%d" % self._id
        
    def read(self, port, raw_packet):
        """Event. Must be called by object himself when the data
        is available in some port

        Just update port-macs table"""
        sender_mac = raw_packet.get('sender_mac', None)
        receiver_mac = raw_packet.get('receiver_mac', None)
        if not sender_mac or not receiver_mac:
            return False # TODO: add logging support
        if not check_mac(sender_mac) or not check_mac(receiver_mac):
            return False # TODO: add logging support

        # check whether receiver_mac matches mac of our port    
        receiver_ports = filter(lambda p: p.mac == receiver_mac,
                                self._ports.ports)
        if not len(receiver_ports):
            return False # foreign packet. TODO: add logging support
        receiver_port = receiver_ports[0]
        if len(receiver_ports) <> 1:
            pass # TODO: add logging support

        self._ports.update_table(receiver_port, sender_mac)
        return True    
        


    def write(self, port, raw_packet):
        pass # TODO: implement me!
    
